package com.sxj.shop.dao.impl;

import com.sxj.shop.dao.UserDao;
import com.sxj.shop.entity.User;
import com.sxj.shop.factory.ObjectFactory;
import com.sxj.shop.rowmapper.UserRowMapper;
import com.sxj.shop.util.JDBCTemplate;
import com.sxj.shop.util.RowMapper;

import java.sql.ResultSet;
import java.util.List;

public class UserDaoImpl implements UserDao {

    private JDBCTemplate<User> jdbcTemplate = (JDBCTemplate<User>) ObjectFactory.getObject("jdbc");

    @Override
    public User selectByUsername(String username) {
        String sql = new StringBuffer()
                .append(" select id,username,password,phone,address ")
                .append(" from t_user ")
                .append(" where username = ? ")
                .toString();
        List<User> users = jdbcTemplate.query(sql, new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet rs) throws Exception {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                return user;
            }
        }, username);
        return users.isEmpty() ? null : users.get(0);
    }

    @Override
    public void insertUser(User user) {
        String sql = new StringBuffer()
                .append(" insert into ")
                .append(" t_user ")
                .append("   (username,password,phone,address)")
                .append(" values ")
                .append("   (?,?,?,?)")
                .toString();
        jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), user.getPhone(), user.getAddress());
    }

    @Override
    public User selectByUsernameAndPassword(String username, String password) {
        String sql = new StringBuffer()
                .append(" select id,username,password,phone,address ")
                .append(" from t_user ")
                .append(" where username = ? ")
                .append(" and password = ?")
                .toString();
        List<User> users = jdbcTemplate.query(sql, new UserRowMapper(), username, password);
        return users.isEmpty() ? null : users.get(0);
    }

    @Override
    public void updatePassword(Integer id, String password) {
        String sql = new StringBuffer()
                .append(" update t_user ")
                .append(" set password = ? ")
                .append(" where id = ?")
                .toString();
        jdbcTemplate.update(sql, password, id);
    }
}
